package com.nsi.service.Impl;

import com.aliyun.oos.demo.AliyunOSSClientUtil;
import com.aliyun.oos.demo.OSSClientConstants;
import com.aliyun.oss.OSSClient;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nsi.common.Const;
import com.nsi.util.RedisUtils;
import com.nsi.common.ResponseCode;
import com.nsi.common.ServerResponse;
import com.nsi.dao.AdvertisementMapper;
import com.nsi.dao.ArticleMapper;
import com.nsi.dao.BoardsMapper;
import com.nsi.dao.ConfigureMapper;
import com.nsi.pojo.Advertisement;
import com.nsi.pojo.Article;
import com.nsi.pojo.Configure;
import com.nsi.service.ArticleCountCommonService;
import com.nsi.service.IArticleService;
import com.nsi.util.FileUtil;
import com.nsi.util.PropertiesUtil;
import com.nsi.vo.Articles;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.stream.Collectors;

/**
 * @author Luo Zhen
 * @create 2018-08-10
 */
@Slf4j
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements IArticleService {

    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private AdvertisementMapper advertisementMapper;
    @Autowired
    private BoardsMapper boardsMapper;
    @Autowired
    private ConfigureMapper configureMapper;
    @Autowired
    private ArticleCountCommonService articleCountCommonService;

    /**
     * 保存文章
     *
     * @param article
     * @return
     */
    @Override
    public ServerResponse saveOn(Article article) {
        if (StringUtils.isEmpty(article.getTitle()) && StringUtils.isEmpty(article.getSummary())) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        //查找模板
        Configure configure = configureMapper.findByType(Const.ARTICLE_TYPE);
        if (configure == null) {
            return ServerResponse.createByErrorMessage("文章模板为空");
        }
        //文件夹路径
        String path = PropertiesUtil.getProperty("article.html.url") + new SimpleDateFormat("yyyyMMdd").format(new Date()) + File.separator;
        String arcitleHTML = getString(article, configure);
        //服务器生成文章路径
        article.setCreateTime(new Date());
        article.setUpdateTime(article.getCreateTime());
        int rowCount = articleMapper.insert(article);
        if (rowCount == 0) {
            return ServerResponse.createByErrorMessage("添加失败");
        }
        //返回自增主键
        int id = article.getId();
        String fileName = FileUtil.writeHtml(id, arcitleHTML, path);
        //上传至阿里云
        String url = uploadFileOos(path, fileName);

        log.info("文章上传成功地址:{}", url);
        Article currentArticle = new Article();
        currentArticle.setId(id);
        currentArticle.setArticleUrl(url);
        rowCount = articleMapper.updateById(currentArticle);
        if (rowCount > 0) {
            return ServerResponse.createBySuccessMessage("添加成功");
        }
        return ServerResponse.createByErrorMessage("添加失败");
    }

    /**
     * 修改文章
     *
     * @param article
     * @return
     */
    @Override
    public ServerResponse updateOn(Article article) {
        if (article.getId() == null) {
            return ServerResponse.createByErrorMessage("参数不合法");
        }
        if (StringUtils.isEmpty(article.getTitle()) && StringUtils.isEmpty(article.getSummary())) {
            return ServerResponse.createByErrorMessage("参数不合法");
        }
        //查找模板
        Configure configure = configureMapper.findByType(Const.ARTICLE_TYPE);
        if (configure == null) {
            return ServerResponse.createByErrorMessage("文章模板为空");
        }
        // 文件夹路径
        String path = PropertiesUtil.getProperty("article.html.url") + new SimpleDateFormat("yyyyMMdd").format(new Date()) + File.separator;
        // 获取文章拼接好字符串
        String arcitleHTML = this.getString(article, configure);
        // 生成文件
        String fileName = FileUtil.writeHtml(article.getId(), arcitleHTML, path);
        //上传至阿里云
        String url = uploadFileOos(path, fileName);
        log.info("上传OOS成功:{}", url);

        article.setArticleUrl(url);
        article.setUpdateTime(new Date());
        int rowCount = articleMapper.updateById(article);
        if (rowCount > 0) {
            return ServerResponse.createBySuccessMessage("修改成功");
        }
        return ServerResponse.createByErrorMessage("修改失败");
    }

    /**
     * 更换文章模板
     *
     * @return
     */
    @Override
    public ServerResponse updateTemplate() {
        List<Integer> articleIds = articleMapper.getId();
        log.info("【文章模板】批量更新：articleIds:{}", articleIds);

        //查找模板
        Configure configure = configureMapper.findByType(Const.ARTICLE_TYPE);
        if (configure == null) {
            return ServerResponse.createByErrorMessage("文章模板为空");
        }
        // 文件夹路径
        String path = PropertiesUtil.getProperty("article.html.url") + new SimpleDateFormat("yyyyMMdd").format(new Date()) + File.separator;
        long startTime = System.currentTimeMillis() / 1000;
        for (Integer id : articleIds) {
            Article article = articleMapper.selectById(id);
            // 获取文章拼接好字符串
            String arcitleHTML = getString(article, configure);
            // 生成文件
            String fileName = FileUtil.writeHtml(article.getId(), arcitleHTML, path);
            //上传至阿里云
            String url = uploadFileOos(path, fileName);
            log.info("修改模板OOS成功:{}", url);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            article.setArticleUrl(url);
            article.setUpdateTime(new Date());
            articleMapper.updateById(article);
        }
        long endTime = System.currentTimeMillis() / 1000;
        long time = startTime - endTime;
        log.info("time:{}", time);
        return ServerResponse.createBySuccessMessage("修改成功");
    }

    /**
     * 获取文章拼接并替换指定字符
     *
     * @param article
     * @param configure
     * @return
     */
    private String getString(Article article, Configure configure) {
        return configure.getTextcontent01()
                .replaceAll("ARTICLE---TITLE", article.getTitle())
                .replaceAll("ARITICLE---SUMMARY", article.getSummary())
                .replaceAll("ARITICLE---WRITER", article.getArticleWriter())
                .replaceAll("ARTICLE---CONTENT", Matcher.quoteReplacement(article.getArticleContent()))
                .replaceAll("ARTICLE---SOURCE---TITLE", article.getArticleSourceTitle())
                .replaceAll("ARTICLE---ARTICLESOURCEADRESS", article.getArticleSourceAdress())
                .replaceAll("ARITICLE---COVER---IMAGE", article.getCoverImage());

    }

    /**
     * 上传文章OOS 返回文件名字
     *
     * @param path
     * @param fileName
     * @return
     */
    private String uploadFileOos(String path, String fileName) {
        File targetFile = new File(path, fileName);
        OSSClient ossClient = AliyunOSSClientUtil.getOSSClient();
        AliyunOSSClientUtil.uploadObject2OSS(ossClient, targetFile, OSSClientConstants.ARTICLE_BACKET_NAME, "article/");
        return PropertiesUtil.getProperty("aliyun.download.url") + "article/" + fileName;
    }

    @Override
    public ServerResponse deleteOn(Integer articleId) {
        if (articleId == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        int rowCount = articleMapper.deleteById(articleId);
        if (rowCount > 0) {
            return ServerResponse.createBySuccessMessage("删除成功");
        }
        return ServerResponse.createByErrorMessage("删除失败");
    }

    @Override
    public ServerResponse managerList(String siftType, String keyword, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Article> articleList = articleMapper.selectAllList(siftType, keyword);
        PageInfo pageInfo = new PageInfo(articleList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse list(String siftType, String articleCat, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Article> articleList = articleMapper.findArticleBySiftTypeAndArticleCat(siftType, articleCat);
        PageInfo pageInfo = new PageInfo(articleList);
        return ServerResponse.createBySuccess(pageInfo);
    }


    @Override
    public String baiduUrlList(String siftType, String articleCat, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Article> articleList = articleMapper.findArticleBySiftTypeAndArticleCat(siftType, articleCat);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < articleList.size(); i++) {
            System.out.println(articleList.get(i).getArticleUrl());
            sb.append(articleList.get(i).getArticleUrl() + ",");
        }
        String outString = sb.toString().substring(0, sb.toString().length() - 1);
        return outString;
    }


    @Override
    public ServerResponse detailOn(Integer articleId) {
        if (articleId == null) {
            return ServerResponse.createByErrorMessage("参数不合法");
        }
        Article article = this.selectById(articleId);

        // 添加文章阅读量
        articleCountCommonService.addWatchNum(article);

        return ServerResponse.createBySuccess(article);
    }

    /**
     * 根据boardName 返回跳转路径
     *
     * @return
     */
    @Override
    public ServerResponse findUrlByBoardName() {
        String redirectUrl = boardsMapper.findByBoardname(Const.BOARDNAME);
        if (redirectUrl != null) {
            return ServerResponse.createBySuccess(redirectUrl);
        }
        return null;
    }


    @Override
    public ServerResponse updateUrlByBoardName(String sid) {
        int rowCount = boardsMapper.updateSidByBoardName(sid, Const.BOARDNAME);
        if (rowCount > 0) {
            return ServerResponse.createBySuccess("文章跳转地址修改成功");
        }
        return ServerResponse.createByErrorMessage("文章跳转地址修改失败");
    }

    /**
     * 文章页面访问统计模块,文章浏览量+1
     *
     * @param articleId
     * @return
     */
    @Override
    public ServerResponse pageStatistics(Integer articleId) {

        if (articleId == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        String key = null;
        int keyNum = 0;
        if (RedisUtils.searchRedis(articleId.toString()) == null) {
            RedisUtils.addRedis(articleId.toString(), "1");
        } else {
            key = RedisUtils.searchRedis(articleId.toString());
            keyNum = Integer.parseInt(key) + 1;
            RedisUtils.addRedis(articleId.toString(), String.valueOf(keyNum));
            System.out.println("访问统计：" + articleId.toString() + ":" + keyNum);
        }

        return ServerResponse.createBySuccessMessage("success");
    }

    /**
     * 访问统计更新
     *
     * @param articleId
     * @return
     */
    @Override
    public ServerResponse refreshStatistics(Integer articleId) {
        if (articleId == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        //redis存储
        String keyNum = RedisUtils.searchRedis(articleId.toString());
        System.out.println("访问统计：" + articleId.toString() + ":" + keyNum);
        return ServerResponse.createBySuccessMessage(keyNum);
    }


    /**
     * 页面分销Fcode统计模块,浏览量+1
     *
     * @param Fcode
     * @return
     */
    @Override
    public ServerResponse FcodeStatistics(String Fcode) {

        if (Fcode == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        //redis存储
        String key = null;
        int keyNum = 0;
        if (RedisUtils.searchRedis(Fcode) == null) {
            RedisUtils.addRedis(Fcode, "1");
        } else {
            key = RedisUtils.searchRedis(Fcode);
            keyNum = Integer.parseInt(key) + 1;
            RedisUtils.addRedis(Fcode, String.valueOf(keyNum));
            System.out.println("Fcode访问统计：" + Fcode + ":" + keyNum);
        }
        return ServerResponse.createBySuccessMessage("success");
    }

    /**
     * 页面分销Fcode统计模块-返回访问量
     *
     * @param Fcode
     * @return
     */
    @Override
    public ServerResponse ShowFcodeStatistics(String Fcode) {
        if (Fcode == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        //redis存储
        String keyNum = RedisUtils.searchRedis(Fcode);
        System.out.println("访问统计：" + Fcode + ":" + keyNum);
        return ServerResponse.createBySuccessMessage(keyNum);
    }

    /**
     * 广告组件-获取广告
     *
     * @param typeName
     * @return
     */
    @Override
    public ServerResponse getArticleAd(String typeName) {
        //1、返回查询结果值
        List<Advertisement> list = advertisementMapper.selectByTypeName(typeName);
        return ServerResponse.createBySuccess(list);
    }

    /**
     * 广告组件-设置广告
     *
     * @param advertisement
     * @return
     */
    @Override
    public ServerResponse setArticleAd(Advertisement advertisement) {
        //1、修改数据
        int Count = advertisementMapper.updateByPrimaryKey(advertisement);
        if (Count >= 0) {
            return ServerResponse.createBySuccessMessage("success");
        } else {
            return ServerResponse.createByErrorMessage("修改失败");
        }
    }

    /**
     * 返回拼好文章详情
     *
     * @return
     */
    @Override
    public ServerResponse queryByArticle() {
        List<Article> articleList = articleMapper.queryByArticle();
        List<String> list = new ArrayList<>();
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(articleList)) {
            for (Article article : articleList) {
                String articleHtml = assemble(article);
                list.add(articleHtml);
            }
        }
        return ServerResponse.createBySuccess(list);
    }

    @Override
    public ServerResponse checkTitle(String title) {
        if (StringUtils.isBlank(title)) {
            return ServerResponse.createByErrorMessage("参数不合法");
        }
        Article article = articleMapper.findArticleByTitle(title);
        if (article != null) {
            return ServerResponse.createByError(article);
        } else {
            return ServerResponse.createBySuccess();
        }
    }

    @Override
    public ServerResponse findArticleList(int pageNum, int pageSize, String searchKey) {
        PageHelper.startPage(pageNum, pageSize);
        List<Article> articleList = articleMapper.selectBySearchKey(searchKey);
        PageInfo pageInfo = new PageInfo<>(articleList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse findArticleName(String keyword) {
        List<Article> listArticle = articleMapper.findTitleOrSummaryOrContentLike(keyword);
        if (!CollectionUtils.isEmpty(listArticle)) {
            List<Articles> articles = listArticle.stream()
                    .map(e -> new Articles(e.getId(), e.getTitle()))
                    .collect(Collectors.toList());
            return ServerResponse.createBySuccess(articles);
        }
        return ServerResponse.createBySuccess();
    }

    /**
     * 文章DTO 模型
     *
     * @param article
     * @return
     */
    private String assemble(Article article) {
        return "<h1><a href='" + article.getArticleUrl() + "'>" + article.getTitle() + "</a></h1>";
    }

}

